﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Com.CMS263.Util
{
    /// <summary>
    /// cookie验证码
    /// </summary>
    public static class BusinessValidateCodeCookie
    {
        public static readonly string BusinessCookieName = "BusinessValidateCodeCookie";
        /// <summary>
        /// 保存验证码到cookie
        /// </summary>
        /// <param name="code"></param>
        public static void SaveToCookie(string code)
        {
            HttpCookie cookie = new HttpCookie(BusinessCookieName);
            cookie.Value = code;
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 获取cookie中验证码
        /// </summary>
        /// <returns></returns>
        public static string GetValidateCode()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[BusinessCookieName];
            return cookie == null ? "" : cookie.Value;
        }
    }
    /// <summary>
    /// 注册验证码
    /// </summary>
    public static class BusinessRegisterValidateCode
    {
        public static readonly string BusinessCookieName = "BusinessRegisterValidateCode";
        /// <summary>
        /// 保存验证码到cookie
        /// </summary>
        /// <param name="code"></param>
        public static void SaveToCookie(string code)
        {
            HttpCookie cookie = new HttpCookie(BusinessCookieName);
            cookie.Value = code;
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 获取cookie中验证码
        /// </summary>
        /// <returns></returns>
        public static string GetValidateCode()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[BusinessCookieName];
            return cookie == null ? "" : cookie.Value;
        }
    }
    public static class BusinessLoginCookie
    {
        //最后一次登陆超时的用户名称(永不过期)
        public const string BusinessLoginCookieLastOverTimeUserName = "BusinessLoginInfoLastOverTimeUserName";
        public const string BusinessLoginCookieName = "BusinessLoginInfo";
        public const int ExpiredMinute = 30;
        /// <summary>
        /// cookies的域
        /// </summary>
        public static string CookiesDomain = "";

        /// <summary>
        /// 保存登录cookie
        /// </summary>
        /// <param name="info"></param>
        public static void SaveBusinessLoginInfo(BusinessLoginInfo info)
        {
            HttpCookie cookie = new HttpCookie(BusinessLoginCookieName);
            if (!string.IsNullOrEmpty(CookiesDomain))
            {
                cookie.Domain = CookiesDomain;
            }
            cookie.Values.Add("NE", info.UserName);
            cookie.Values.Add("AU", info.Authentication);
            cookie.Values.Add("ID", info.UserID.ToString());
            cookie.Values.Add("AT", info.ActionTime.ToString("yyyy-MM-dd HH:mm:ss"));
            HttpContext.Current.Response.AppendCookie(cookie);

            #region 最后一次登陆超时的用户名称(永不过期)
            HttpCookie cookie2 = new HttpCookie(BusinessLoginCookieLastOverTimeUserName);
            cookie2.Expires = DateTime.MaxValue;
            cookie2.Values.Add("NE", info.UserName);
            HttpContext.Current.Response.AppendCookie(cookie2);
            #endregion
        }
        /// <summary>
        /// 清除登录cookie
        /// </summary>
        public static void ClearBusinessLoginInfo()
        {
            HttpCookie cookie = new HttpCookie(BusinessLoginCookieName);
            cookie.Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies.Add(cookie);

            HttpCookie cookie2 = new HttpCookie(BusinessLoginCookieLastOverTimeUserName);
            cookie2.Expires = DateTime.MinValue;
            HttpContext.Current.Response.Cookies.Add(cookie2);
        }
        /// <summary>
        /// 计算认证信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static string GetAuthentication(BusinessLoginInfo info)
        {
            //return StrUtil.Md5(info.ToString());
            //用哈希码，md5太慢
            return (info.ToString().GetHashCode() + 999).ToString();
        }

        /// <summary>
        /// 获取最后一次登陆超时的用户名称(永不过期)
        /// </summary>
        /// <returns></returns>
        public static string BusinessGetLoginLastOverTimeUserName()
        {
            string username = null;
            HttpCookie cookie = HttpContext.Current.Request.Cookies[BusinessLoginCookieLastOverTimeUserName];
            if (cookie != null)
                username = cookie.Values["NE"];
            return username;
        }

        /// <summary>
        /// 获取登录信息，超时将返回null
        /// </summary>
        /// <returns></returns>
        public static BusinessLoginInfo GetBusinessLoginInfo()
        {
            BusinessLoginInfo info = null;
            HttpCookie cookie = HttpContext.Current.Request.Cookies[BusinessLoginCookieName];
            if (cookie != null)
            {
                DateTime ActionTime = DateTime.Parse(cookie.Values["AT"]);
                if (IsExpired(ActionTime))
                {
                    ClearBusinessLoginInfo();
                }
                else
                {
                    info = new BusinessLoginInfo();
                    info.ActionTime = DateTime.Now;

                    info.UserID = int.Parse(cookie.Values["ID"]);
                    //info.CreateTime = DateTime.Parse(cookie.Values["CreateTime"]);
                    info.UserName = cookie.Values["NE"];
                    info.Authentication = cookie.Values["AU"];
                    SaveBusinessLoginInfo(info);
                }

            }
            return info;
        }

        /// <summary>
        /// 判断是否过期
        /// </summary>
        /// <param name="ActionTime"></param>
        /// <returns></returns>
        private static bool IsExpired(DateTime ActionTime)
        {
            //return DateTime.Now.AddMinutes(ExpiredMinute) > ActionTime;
            return ActionTime.AddMinutes(ExpiredMinute) < DateTime.Now;
        }

        /// <summary>
        /// 验证合法性（是否被篡改）
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static bool Authenticate(BusinessLoginInfo info)
        {
            string Authentication = GetAuthentication(info);
            return info.Authentication == Authentication;
        }

        /// <summary>
        /// 是否已登录（null或被篡改将返回false）
        /// </summary>
        /// <returns></returns>
        public static bool IsBusinessUserLogin()
        {
            BusinessLoginInfo info = GetBusinessLoginInfo();
            return (info != null && Authenticate(info));
        }

        public static void Check()
        {
            BusinessLoginInfo info = GetBusinessLoginInfo();
            if (!(info != null && Authenticate(info)))
            {
                StringUtil.Alert("您还没有登录,或者登陆已超时，请重新登录", "/index.aspx");
            }
        }
    }
    /// <summary>
    /// 用于记录用户登录信息的类
    /// </summary>
    public class BusinessLoginInfo
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public int UserID { set; get; }
        /// <summary>
        /// 登录用户名
        /// </summary>
        public string UserName { set; get; }
        /// <summary>
        /// 认证信息
        /// </summary>
        public string Authentication { set; get; }

        /// <summary>
        /// 活动时间
        /// </summary>
        public DateTime ActionTime { set; get; }


        ///// <summary>
        ///// 创建时间
        ///// </summary>
        //public DateTime CreateTime { set; get; }



        private readonly string Confusion = "2#d_+c.dSo%makelumer";

        public BusinessLoginInfo()
        {
        }


        public BusinessLoginInfo(string UserName, int UserID)
        {
            this.UserName = UserName;
            this.UserID = UserID;
            this.ActionTime = DateTime.Now;
            this.Authentication = BusinessLoginCookie.GetAuthentication(this);
        }
        /// <summary>
        /// 返回UserName+CreateTime+Confusion
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return this.UserName + Confusion + this.UserID.ToString();
        }
    }

}
